import os
import threading
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service


class Driver:
    thread_local = threading.local()

    filename = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    driver_path = os.path.join(filename, "config", "chromedriver.exe")

    def get_driver(self, url, options=None):
        if not hasattr(self.thread_local, "driver") or self.thread_local.driver is None:
            service = Service(self.driver_path)

            if options is None:
                chrome_options = Options()
                chrome_options.add_argument("--start-maximized")
                chrome_options.add_argument("--disable-gpu")
                chrome_options.add_argument("--no-sandbox")

            self.thread_local.driver = webdriver.Chrome(service=service, options=options)

            self.thread_local.driver.get(url)

        return self.thread_local.driver

    def quit_driver(self):
        if hasattr(self.thread_local, "driver") and self.thread_local.driver is not None:
            self.thread_local.driver.quit()
            self.thread_local.driver = None

    def get_current_driver(self):
        if hasattr(self.thread_local, "driver"):
            return self.thread_local.driver
        raise Exception(f"线程 {threading.current_thread().name} 未创建 driver 实例")
